import { useSearchParams, useNavigate } from "react-router-dom";
import { useState, useEffect } from "react";
import HCTitle from "@/components/hc-title";
import EditContent from "./components/EditContent";
import ChildDataset from "./components/ChildDataset";
import api from "@/api";
import { message, Modal } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { closeCurrentTab } from "@/store/modules/tabListSlice";

const Edit = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const tabList = useSelector(state => state.tabList.tabList)

  const [form, setForm] = useState({});
  const [childDataset, setChildDataset] = useState([])
  const [initialValues, setInitialValues] = useState({
    name: '',
    remark: '',
  })

  const [searchParams] = useSearchParams();
  const id = searchParams.get("id");
  const isNew = id === null;
  const title = isNew ? "新建数据集" : `编辑数据集ID${id}`;

  const btnGroup = [
    { text: "保存", type: "primary", action: "handleSave" },
  ];
  if (!isNew) {
    btnGroup.push({ text: "删除", type: "primary", danger: true, action: "handleDel" })
  }

  const getDatasetDetail = () => {
    api.dataset.getChildrenById({id: 0}).then((res) => {
      setInitialValues(res.data[res.data.length - 1])
      setForm(form => ({...form, ...res.data[res.data.length - 1]}))
    });
  }

  const getChildDataset = () => {
    api.dataset.getChildrenById({id}).then((res) => {
      res.data.forEach(item => item.editId = item.id)
      setChildDataset(res.data)
    })
  }

  const handleSave = () => {
    if (isNew) {
      // 新增 - 先保存父集合，再保存子集合
      const pDatasetParams = {
        name: form.name,
        remark: form.remark,
        parent_id: 0,
        parent_name: 'root'
      }
      api.dataset.add(pDatasetParams).then((res) => {
        // TODO 接口返回插入的信息，获取parentid跟parentname
        api.dataset.getChildrenById({id: 0}).then((res) => {
          const target = res.data[res.data.length - 1]
          if (childDataset.length) {
            const childParams = childDataset.map(item => ({
              ...item,
              parent_id: target.id,
              parent_name: target.name
            }))
            api.dataset.add(childParams).then((res) => {
              message.success("保存成功")
              const lastTab = tabList[tabList.length - 2]
              navigate(lastTab.path)
              dispatch(closeCurrentTab())
            })
          } else {
            message.success("保存成功")
            const lastTab = tabList[tabList.length - 2]
            navigate(lastTab.path)
            dispatch(closeCurrentTab())
          }
        });
      })
    } else {
      // 更新
      api.dataset.update(form).then((res) => {
        message.success("保存成功")
        const lastTab = tabList[tabList.length - 2]
        navigate(lastTab.path)
        dispatch(closeCurrentTab())
      })
    }
  }

  const handleDel = () => {
    Modal.confirm({
      title: "提示",
      content: `确认删除数据集【${form.name}】吗？`,
      okText: "确认",
      cancelText: "取消",
      centered: true,
      onOk: () => {
        api.dataset.delete(form).then((res) => {
          message.success("删除成功");
          const lastTab = tabList[tabList.length - 2]
          navigate(lastTab.path)
          dispatch(closeCurrentTab())
        });
      },
    })
  }

  useEffect(() => {
    if (!isNew) {
      getDatasetDetail()
      getChildDataset()
    }
  }, [id])

  return (
    <div>
      <HCTitle
        title={title}
        btnGroup={btnGroup}
        handleSave={handleSave}
        handleDel={handleDel}
      ></HCTitle>
      <EditContent
        initialValues={initialValues} 
        setForm={setForm}
        childDataset={childDataset}
        setChildDataset={setChildDataset}  
      />
      <ChildDataset
        isNew={isNew}
        form={form}
        list={childDataset}
        setList={setChildDataset}
        getChildDataset={getChildDataset}
      ></ChildDataset>
    </div>
  );
};

export default Edit;
